javascript 中五种实现B继承A的方法 1.继承第一种方式:对象冒充 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 function Parent (userName ) { this .userName = userName; this .hello = function ( ) { alert(this .userName) } } function Child (userName, passWord ) { this .method = Parent; this .method(userName); delete this .method; this .passWord = passWord; this .world = function ( ) { alert(this .passWord); } } var parent = new Parent('wujia' ); var child = new Child('guozheng' , '123' ); parent.hello(); child.hello(); child.world();
2.继承第二种方式:call()方法
第一个参数的值赋值给类中出现的this,第二个参数开始依次赋值给类所接受的参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 function test (str ) { alert('1:' + this .name + ' ' + str) } var object = new Object (); object.name = 'wujia' ; test.call(object, 'guozheng' ); function Parent1 (userName ) { this .userName = userName; this .hello = function ( ) { alert('2:' + this .userName) } } function Child1 (userName, passWord ) { Parent1.call(this , userName); this .passWord = passWord; this .world = function ( ) { alert('3:' + this .passWord); } } var parent = new Parent1('jia' ); var child = new Child1('zheng' , '123' ); parent.hello(); alert('2' ) child.hello(); alert('3' ) child.world();
3.继承第三种方式:apply()方法
第一个参数为赋值给类中出现的this,第二个参数为数组类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 function Parent2 (userName ) { this .userName = userName; this .hello = function ( ) { alert('2:' + this .userName) } } function Child2 (userName, passWord ) { Parent2.apply(this , new Array (userName)); this .passWord = passWord; this .world = function ( ) { alert('3:' + this .passWord); } } var parent = new Parent2('jia1' ); var child = new Child2('zheng2' , '1233' ); parent.hello(); child.hello(); child.world();
4.继承第四种方式:原型链方式
即子类通过prototype 将所有在父类中通过prototype追加的属性和方法都追加到Child4,从而实现继承
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 function Person ( ) { Person.prototype.hello = "hello" ; Person.prototype.sayHello = function ( ) { alert(this .hello); } } function Child4 ( ) {} Child4.prototype = new Person(); Child4.prototype.world = 'world' ; Child4.prototype.sayWorld = function ( ) { alert(this .world); } var city = new Child4; city.sayHello(); city.sayWorld();
5.继承第五种方式:混合方法(混合call和原型链方式) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 function Parent5 (hello ) { this .hello = hello; } Parent5.prototype.sayHello = function ( ) { alert(this .hello) } function Child5 (hello, world ) { Parent5.call(this , hello); this .world = world; } Child5.prototype = new Parent5(); Child5.prototype.sayWorld = function ( ) { alert(this .world); } var city = new Child5('wjia' , 'zheng' ); city.sayHello(); city.sayWorld();